package com.wsx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsx.common.CustomException;
import com.wsx.common.R;
import com.wsx.entity.Category;
import com.wsx.entity.Dish;
import com.wsx.entity.Setmeal;
import com.wsx.mapper.CategoryMapper;
import com.wsx.mapper.DishMapper;
import com.wsx.mapper.SetmealMapper;
import com.wsx.service.CategoryService;
import com.wsx.service.DishService;
import com.wsx.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加分类
     */
    @Override
    public void insertCategory(Category category) {
        categoryMapper.insertCategory(category);
    }

    /**
     * 根据id修改分类
     */
    @Override
    public void updateByCategory(Category category) {
        categoryMapper.updateByCategory(category);
    }

    /**
     * 根据id删除分类，删除之前需要进行判断
     */
    @Override
    public void remove(Long id) {
        //添加查询条件，根据分类id进行查询菜品数据
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        Integer count1 = dishMapper.selectCount(dishLambdaQueryWrapper);
        //如果已经关联，抛出一个业务异常
        if(count1 > 0){
            throw new CustomException("当前分类下关联了菜品，不能删除");//已经关联菜品，抛出一个业务异常
        }

        //查询当前分类是否关联了套餐，如果已经关联，抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        Integer count2 = setmealMapper.selectCount(setmealLambdaQueryWrapper);
        if(count2 > 0){
            throw new CustomException("当前分类下关联了套餐，不能删除");//已经关联套餐，抛出一个业务异常
        }

        //正常删除分类
        super.removeById(id);
    }


}